package com.jielin.handling.util.pdfutil;

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.PDimension;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

/**
 * @ClassName PdfUtil
 * @Description pdf操作工具类
 * @Author WR
 * @Date
 * @Version 1.0
 */
public class PdfUtil {
	public static final String FILETYPE_JPG = "jpg";
	public static final String SUFF_IMAGE = "." + FILETYPE_JPG;
	public static final float ZOOM = 1L;

	/**
	 * 
	 * 将指定pdf文件的首页转换为指定路径的缩略图
	 * 
	 * @param filePath  原文件路径，例如d:/test.pdf
	 * 
	 * @param imagePath 图片生成路径，例如 d:/test-1.jpg
	 * 
	 * @param zoom      缩略图显示倍数，1表示不缩放，0.3则缩小到30%
	 * 
	 * @throws PDFException, PDFSecurityException, IOException, InterruptedException
	 * 
	 */
	public static void tranfer(String filePath, String imagePath, float zoom)
			throws PDFException, PDFSecurityException, IOException, InterruptedException {
		// ICEpdf document class
		Document document = null;

		float rotation = 0f;

		document = new Document();
		document.setFile(filePath);
		// maxPages = document.getPageTree().getNumberOfPages();

		BufferedImage img = (BufferedImage) document.getPageImage(0, GraphicsRenderingHints.SCREEN,
				Page.BOUNDARY_CROPBOX, rotation, zoom);

		Iterator iter = ImageIO.getImageWritersBySuffix(FILETYPE_JPG);
		ImageWriter writer = (ImageWriter) iter.next();
		File outFile = new File(imagePath);
		FileOutputStream out = new FileOutputStream(outFile);
		ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
		writer.setOutput(outImage);
		writer.write(new IIOImage(img, null, null));
	}

	/**
	 * 转换pfd每一页为jpg缩略图大图
	 *
	 * @param is   输入流
	 * @param os   输出流
	 * @param zoom 缩略图缩放比例
	 * @return
	 * @throws PDFException
	 * @throws PDFSecurityException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void tranfer(InputStream is, OutputStream os, float zoom)
			throws PDFException, PDFSecurityException, IOException, InterruptedException {
		// ICEpdf document class
		Document document = null;
		float rotation = 0f;
		document = new Document();
		document.setInputStream(is, null);
		// 获取pdf总页数
		int pages = document.getNumberOfPages();
		if (pages > 0) {
			tranferPer(document, rotation, zoom, os, 0);
		}
	}


	public static void main(String[] args) {
		try {
			tranfer("C:\\data\\recordpdfs\\陈章的笔录2019_6_28_109788249.pdf", 1);
		} catch (PDFException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PDFSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 转换pfd第一页为jpg缩略图大图
	 *
	 * @param filepath
	 * @param zoom
	 * @throws PDFException
	 * @throws PDFSecurityException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void tranfer1(String filepath, float zoom)
			throws PDFException, PDFSecurityException, IOException, InterruptedException {
		// ICEpdf document class
		Document document = null;
		float rotation = 0f;
		document = new Document();
		document.setFile(filepath);
		// 创建以pdf文件名为名称的文件夹保存pdf缩略图
		File file = new File(filepath.substring(0, filepath.lastIndexOf(".")));
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在");
			file.mkdir();
		} else {
			System.out.println("//目录存在");
		}
		String imagepath = "";
		// 设置文件名
		imagepath = jpgFilename(filepath, 0);
		// 转换首页为jpg缩略图
		tranferPer(document, rotation, zoom, imagepath, 0);
	}

	/**
	 * 转换pfd每一页为jpg缩略图大图
	 *
	 * @param filepath pfd文件路径
	 * @param zoom     缩略图缩放比例
	 * @throws PDFException
	 * @throws PDFSecurityException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static String tranfer(String filepath, float zoom)
			throws PDFException, PDFSecurityException, IOException, InterruptedException {
		// ICEpdf document class
		Document document = null;
		float rotation = 0f;
		document = new Document();
		document.setFile(filepath);
		// 获取pdf总页数
		int pages = document.getNumberOfPages();
		if (pages > 0) {
			// 创建以pdf文件名为名称的文件夹保存pdf缩略图
			File file = new File(filepath.substring(0, filepath.lastIndexOf(".")));
			if (!file.exists() && !file.isDirectory()) {
				System.out.println("//不存在");
				file.mkdir();
			} else {
				System.out.println("//目录存在");
			}
			String imagepath = "";
//			String smallimagepath = "";
			// 将每一页的pdf转换为jpg缩略图
//			for (int i = 0; i < pages; i++) {
//				// 设置文件名
//				imagepath = jpgFilename(filepath, i);
//				tranferPer(document, rotation, zoom, imagepath, i);
//				// 由缩略图生成指定宽高的jpg小图
//				smallimagepath = imagepath.substring(0, imagepath.lastIndexOf(".")) + "-small" + ".jpg";
//				zoomImage(imagepath, smallimagepath, 200, 300);
//			}
			// 将第一页的pdf转换为jpg缩略图
			// 设置文件名
			imagepath = jpgFilename(filepath, 0);
			tranferPer(document, rotation, zoom, imagepath, 0);
			return imagepath;
		}
		return "";
	}

	/**
	 * 设置jpg文件名
	 *
	 * @param filepath
	 * @param index
	 * @return
	 */
	public static String jpgFilename(String filepath, int index) {
		String jpgFilename = "";
		String folder = "";
		index++;
		if (filepath != null && !filepath.equals("")) {
//			folder = filepath.substring(filepath.lastIndexOf(File.separator) + 1, filepath.lastIndexOf("."));
//			jpgFilename = filepath.substring(0, filepath.lastIndexOf(".")) + File.separator + folder + "-" + index + "."
			folder = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.lastIndexOf("."));
			jpgFilename = filepath.substring(0, filepath.lastIndexOf(".")) + "/" + folder + "-" + index + "."
					+ FILETYPE_JPG;
		}
		return jpgFilename;
	}

	/**
	 * 转换一页pdf为jpg缩略图大图
	 *
	 * @param document
	 * @param rotation
	 * @param zoom
	 * @param imagepath
	 * @throws PDFException
	 * @throws PDFSecurityException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void tranferPer(Document document, float rotation, float zoom, String imagepath, int index)
			throws PDFException, PDFSecurityException, IOException, InterruptedException {
		float scale = 1f;
//		Page page = document.getPageTree().getPage(index, Object.class);
		Page page = document.getPageTree().getPage(index);
		page.init();
		PDimension sz = page.getSize(Page.BOUNDARY_CROPBOX, rotation, scale);
		int pageWidth = (int) sz.getWidth();
		int pageHeight = (int) sz.getHeight();
		BufferedImage image = new BufferedImage(pageWidth, pageHeight, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.createGraphics();
		page.paint(g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);
		g.dispose();
		// capture the page image to file
		try {
			System.out.println("转换第 " + (index + 1) + " 页");
			File file = new File(imagepath);
			ImageIO.write(image, "jpg", file);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		image.flush();
		// 由缩略图生成指定宽高的jpg小图
//		String smallimagepath = imagepath.substring(0, imagepath.lastIndexOf(".")) + "-small" + ".jpg";
//		zoomImage(imagepath, smallimagepath, 88, 126);
	}

	/**
	 * 转换一页pdf为jpg缩略图大图
	 *
	 * @param document
	 * @param rotation
	 * @param zoom
	 * @param os
	 * @param index
	 * @throws PDFException
	 * @throws PDFSecurityException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void tranferPer(Document document, float rotation, float zoom, OutputStream os, int index)
			throws PDFException, PDFSecurityException, IOException, InterruptedException {
		float scale = 1f;
		Page page = document.getPageTree().getPage(index);
		page.init();
		PDimension sz = page.getSize(Page.BOUNDARY_CROPBOX, rotation, scale);
		int pageWidth = (int) sz.getWidth();
		int pageHeight = (int) sz.getHeight();
		BufferedImage image = new BufferedImage(pageWidth, pageHeight, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.createGraphics();
		page.paint(g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);
		g.dispose();
		try {
			System.out.println("转换第 " + (index + 1) + " 页");
			ImageIO.write(image, FILETYPE_JPG, os);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		image.flush();
	}

	/**
	 * 由缩略图生成指定宽高的jpg小图
	 * 
	 * @param srcFileName
	 * @param tagFileName
	 * @param width
	 * @param height
	 */
	public static void zoomImage(String srcFileName, String tagFileName, int width, int height) {
		try {
			BufferedImage bi = ImageIO.read(new File(srcFileName));
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(bi, 0, 0, width, height, null);
			ImageIO.write(tag, "jpg", new File(tagFileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
